import apiConfig from '../config/api.js';

class AuthService {
  constructor() {
    this.tokenKey = 'apiviewer_token';
    this.userKey = 'apiviewer_user';
  }

  // 动态获取基础URL
  get baseURL() {
    return apiConfig.getAuthURL();
  }

  // 通用的fetch请求方法
  async request(url, options = {}) {
    const token = this.getToken();
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...(token && { Authorization: `Bearer ${token}` }),
        ...options.headers,
      },
      ...options,
    };

    try {
      const response = await fetch(url, config);
      
      // 处理认证错误
      if (response.status === 401) {
        this.logout();
        window.location.reload();
        throw new Error('认证失败');
      }

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || `HTTP ${response.status}`);
      }

      return response;
    } catch (error) {
      throw error;
    }
  }

  // 注册
  async register(userData) {
    try {
      const response = await this.request(apiConfig.getAuthURL('/register'), {
        method: 'POST',
        body: JSON.stringify(userData),
      });
      const data = await response.json();
      return { success: true, data };
    } catch (error) {
      return { 
        success: false, 
        error: error.message || '注册失败' 
      };
    }
  }

  // 登录
  async login(credentials) {
    try {
      const response = await this.request(apiConfig.getAuthURL('/login'), {
        method: 'POST',
        body: JSON.stringify(credentials),
      });
      const data = await response.json();
      const { access_token, token_type, expires_in, user_role } = data;
      
      console.log('登录响应数据:', data);
      
      // 保存令牌
      this.setToken(access_token);
      
      // 获取用户信息
      const userInfo = await this.getCurrentUser();
      console.log('获取用户信息结果:', userInfo);
      
      if (userInfo.success) {
        // 确保用户信息包含角色
        const userData = userInfo.data;
        if (!userData.role && user_role) {
          userData.role = user_role;
        }
        console.log('保存的用户数据:', userData);
        this.setUser(userData);
      }
      
      return { success: true, data };
    } catch (error) {
      console.error('登录失败:', error);
      return { 
        success: false, 
        error: error.message || '登录失败' 
      };
    }
  }

  // 登出
  async logout() {
    try {
      await this.request(apiConfig.getAuthURL('/logout'), {
        method: 'POST',
      });
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      this.removeToken();
      this.removeUser();
    }
  }

  // 获取当前用户信息
  async getCurrentUser() {
    try {
      const response = await this.request(apiConfig.getAuthURL('/me'));
      const data = await response.json();
      return { success: true, data };
    } catch (error) {
      return { 
        success: false, 
        error: error.message || '获取用户信息失败' 
      };
    }
  }

  // 获取职位列表
  async getPositions() {
    try {
      const response = await this.request(apiConfig.getAuthURL('/positions'));
      const data = await response.json();
      return { success: true, data };
    } catch (error) {
      return { 
        success: false, 
        error: error.message || '获取职位列表失败' 
      };
    }
  }

  // 验证令牌
  async verifyToken() {
    try {
      await this.request(apiConfig.getAuthURL('/verify'));
      return true;
    } catch (error) {
      return false;
    }
  }

  // 令牌管理
  setToken(token) {
    localStorage.setItem(this.tokenKey, token);
  }

  getToken() {
    return localStorage.getItem(this.tokenKey);
  }

  removeToken() {
    localStorage.removeItem(this.tokenKey);
  }

  // 用户信息管理
  setUser(user) {
    localStorage.setItem(this.userKey, JSON.stringify(user));
  }

  getUser() {
    const user = localStorage.getItem(this.userKey);
    return user ? JSON.parse(user) : null;
  }

  removeUser() {
    localStorage.removeItem(this.userKey);
  }

  // 检查是否已登录
  isAuthenticated() {
    return !!this.getToken();
  }

  // 初始化认证状态（页面加载时调用）
  async initializeAuth() {
    console.log('开始初始化认证状态...');
    
    const token = this.getToken();
    console.log('获取到的token:', token ? '存在' : '不存在');
    
    if (!token) {
      return { isAuthenticated: false };
    }

    const isValid = await this.verifyToken();
    console.log('token验证结果:', isValid);
    
    if (!isValid) {
      this.logout();
      return { isAuthenticated: false };
    }

    const user = this.getUser();
    console.log('本地存储的用户信息:', user);
    
    if (!user) {
      console.log('本地无用户信息，从服务器获取...');
      const userInfo = await this.getCurrentUser();
      console.log('从服务器获取的用户信息:', userInfo);
      
      if (userInfo.success) {
        this.setUser(userInfo.data);
        return { isAuthenticated: true, user: userInfo.data };
      }
    }

    return { isAuthenticated: true, user };
  }
}

export default new AuthService(); 